package com.zhaojonhy.zhaopangwb.ui;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.legacy.FriendshipsAPI;
import com.zhaojonhy.zhaopangwb.R;
import com.zhaojonhy.zhaopangwb.adapter.StatusFriendAdapter;
import com.zhaojonhy.zhaopangwb.bean.User;
import com.zhaojonhy.zhaopangwb.bean.userFriendShips.UserBean;
import com.zhaojonhy.zhaopangwb.bean.userFriendShips.friendShipsFriends;
import com.zhaojonhy.zhaopangwb.utils.AccessTokenKeeper;
import com.zhaojonhy.zhaopangwb.utils.BaseApplication;
import com.zhaojonhy.zhaopangwb.utils.Constants;
import com.zhaojonhy.zhaopangwb.utils.TitleBuilder;
import com.zhaojonhy.zhaopangwb.widget.Pull2RefreshListView;
import com.zhaojonhy.zhaopangwb.widget.UnderlineFor3;


import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/10/24.
 */

public class FriendsActivity extends Activity implements View.OnClickListener,OnCheckedChangeListener{

    private static final String TAG = FriendsActivity.class.getSimpleName() ;

    //关注度接口
    private Oauth2AccessToken mAccessToken;
    private FriendshipsAPI friendsAPI ;

    //菜单栏
    private View title ;

    private RadioGroup rg_user_info;
    private UnderlineFor3 uliv_user_info;

    // 用户相关信息
    private User user;
    private BaseApplication application ;

    //下拉刷新
    private Pull2RefreshListView plv_friend_info ;
    private TextView tv_foot ;
    private View footView ;
    private StatusFriendAdapter adapter ;
    private List<UserBean> users = new ArrayList<UserBean>();

    //初始的页数
    private int curPage = 0 ;
    //下一页
    private int nextPage ;

    private boolean isFollowers = false ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend_info);

        mAccessToken = AccessTokenKeeper.readAccessToken(this) ;
        friendsAPI = new FriendshipsAPI(this, Constants.APP_KEY, mAccessToken) ;

        isFollowers = getIntent().getBooleanExtra("isFollowers",false);
        Log.d(TAG,"followers-->"+"isFollowers :" + isFollowers ) ;

        application = (BaseApplication) getApplication();
        user = application.currentUser ;

        initTitle() ;
        initTab() ;
        initListView() ;
        loadData(0) ;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.titleBarIvLeft :
                finish();
                break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        //根据按键的选中状态来视图，由于RadioButton太多,方法类似，因此提取一个RadioButton的函数
        syncRadioButton(group, checkedId) ;
    }

    private void syncRadioButton(RadioGroup group, int checkedId){
        //获取RadioGroup中被选中的RadioButton的下标
        int index = group.indexOfChild(group.findViewById(checkedId)) ;
        ( (RadioButton)rg_user_info.findViewById(checkedId) ).setChecked(true);
        uliv_user_info.setCurrentItem(index);

    }

    private void initTitle() {
        title = new TitleBuilder(this)
                .setTitleBgRes(R.drawable.userinfo_navigationbar_back)
                .setLeftImage(R.drawable.navigationbar_back_sel)
                .setLeftOnClickListener(this)
                .build();
    }

    //初始化菜单栏
    private void initTab() {

        // 添加到列表中的菜单栏
        rg_user_info = (RadioGroup)findViewById(R.id.rg_user_info);
        uliv_user_info = (UnderlineFor3)findViewById(R.id.uliv_user_info);

        rg_user_info.setOnCheckedChangeListener(this);
        uliv_user_info.setCurrentItem(1);
    }
    private void initListView() {
        plv_friend_info = (Pull2RefreshListView)findViewById(R.id.plv_friend_info) ;
        adapter = new StatusFriendAdapter(this,users) ;
        plv_friend_info.setAdapter(adapter);
        tv_foot = (TextView)findViewById(R.id.tv_foot) ;
        plv_friend_info.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                loadData(0) ;
            }
        });
        plv_friend_info.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                loadData(nextPage) ;
            }
        });
        footView = View.inflate(this , R.layout.footview_loading , null) ;
    }

    private void loadData(final int page) {

        if( isFollowers ){
            friendsAPI.followers(user == null ? -1 : user.getId()
                    , 50, page, false, new RequestListener() {
                        @Override
                        public void onComplete(String response) {
                            //如果是第一页，先清空数据
                            if (page == 0) {
                                users.clear();
                            }

                            curPage = page;

                            Log.d(TAG, "followers-->" + "succesfull" + response);
                            addData(new Gson().fromJson(response, friendShipsFriends.class));
                        }

                        @Override
                        public void onWeiboException(WeiboException e) {
                            Log.d(TAG, "followers-->" + "failed" + e.getMessage());
                        }
                    });
        }else {
            friendsAPI.friends(
                    user == null ? -1 : user.getId()
                    , 50, page, false, new RequestListener() {
                        @Override
                        public void onComplete(String response) {
                            //如果是第一页，先清空数据
                            if (page == 0) {
                                users.clear();
                            }

                            curPage = page;

                            Log.d(TAG, "friends-->" + "succesfull" + response);
                            addData(new Gson().fromJson(response, friendShipsFriends.class));
                        }

                        @Override
                        public void onWeiboException(WeiboException e) {
                            Log.d(TAG, "friends-->" + "failed" + e.getMessage());
                        }
                    }
            );
        }
    }

    private void addData(friendShipsFriends friendShips) {

        nextPage = friendShips.getNext_cursor() ;

        for( UserBean userBean : friendShips.getUsers() ){

            if( !users.contains(userBean)){ //list.contains(Bean) ,防止数据的重复添加
                users.add(userBean) ; //数据添加到集合中
            }
        }

        //可能要开线程
        adapter.notifyDataSetChanged();//适配器更新
        plv_friend_info.onRefreshComplete();

        Log.d(TAG,"allPage --> " + "curPage : "+ curPage + " nextPage : " + nextPage + " totalNumber :" + friendShips.getTotal_number())  ;

        if (curPage <  (int)(friendShips.getTotal_number() * 0.3) ) { //判断是否继续加载 ,当前页小于总页数
            addFootView(plv_friend_info, footView) ; //继续加载
        }else {
            removeFootView(plv_friend_info, footView) ; //移除加载
        }

        //如果当页返回数据小于默认的50
        if( friendShips.getTotal_number() < 50 ) {
            removeFootView(plv_friend_info, footView) ; //移除加载
        }
    }

    private void addFootView(PullToRefreshListView plvHome, View footView ) {
        ListView lv = plvHome.getRefreshableView();
        Log.d(TAG,"lv.getFooterViewsCount()-->" + lv.getFooterViewsCount()) ;
        if(lv.getFooterViewsCount() == 1) {//查看listView的源码此数据是返回listView的List的集合size
            lv.addFooterView(footView); //添加视图，只进行添加一次,当add前count==1 后 count==2
        }
    }

    private void removeFootView(PullToRefreshListView plvHome, View footView) {
        ListView lv = plvHome.getRefreshableView();
        if(lv.getFooterViewsCount() > 1) {
            lv.removeFooterView(footView);
            tv_foot.setVisibility(View.VISIBLE);
        }
    }

}
